import axios from "./axios";
import config from "@/config";
import message from "@/utils/message";
import { token } from "@/utils";
import router from "@/plugins/router";
import { refreshToken } from "@/api/current";

const { getToken, removeToken, getRefreshToken, setToken } = token;

const http = axios.create({ baseUrl: config.baseUrl });

http.interceptors.request.use(
  (config) => {
    config.headers.Authorization = getToken() || "";
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

let isRefreshing = false; // 标记是否正在刷新 token
let requests = []; // 存储待重发请求的数组

const handleTokenExpire = (res) => {
  message.toastError(res.data.message);
  removeToken();
  router.reLaunch("/pages/login");
  return Promise.reject(res.data);
};

const handleRefreshToken = (res) => {
  const { config } = res;
  if (isRefreshing === true) {
    return new Promise((resolve) => {
      requests.push(() => resolve(http(config)));
    });
  }
  const options = {
    headers: { "Refresh-Token": getRefreshToken() },
  };
  isRefreshing = true;
  return refreshToken(options)
    .then((response) => {
      const { accessToken, refreshToken } = response;
      setToken(accessToken, refreshToken);
      // 重发
      config.headers.Authorization = accessToken;
      requests.forEach((request) => request());
      requests = [];
      return http(config);
    })
    .catch((error) => Promise.reject(error))
    .finally(() => {
      isRefreshing = false;
    });
};

const httpCode = {
  401: "请求访问未授权",
  404: "请求地址不存在，请联系管理员",
  500: "服务器错误，请联系管理员",
  default: "服务器连接失败",
};

http.interceptors.response.use(
  (res) => {
    if (res.data.code < 2000 && res.data.message !== "success") {
      message.toast(res.data.message);
      return res.data.data || res.data;
    } else if (res.data.code === 4001 || res.data.code === 4003) {
      return handleTokenExpire(res);
    } else if (res.data.code === 4002 && !res.config.url.includes("/token/refresh")) {
      return handleRefreshToken(res);
    } else if (res.data.message && res.data.message !== "success") {
      message.toastError(res.data.message);
      return Promise.reject(res.data);
    }

    return res.data.data || res.data;
  },
  (error) => {
    if (error.message === "Network Error") {
      message.toastError("后端接口异常");
    } else if (error.message.includes("timeout")) {
      message.toastError("后端请求超时");
    } else {
      message.toastError(httpCode[error?.status || "default"]);
    }
    return Promise.reject(error);
  }
);

export default http;
